import React from 'react'
import {connect} from 'react-redux'
import { Button, Form, Select, Alert, Switch, Col, InputNumber, Popover } from 'antd'
import { message } from 'antd';
import {messages} from "share/common";
import 'styles/finance-setting/auto-audit/auto-audit-rule.scss'
import autoAuditService from 'containers/finance-setting/auto-audit/auto-audit.service'
import Chooser from "components/chooser";
import config from "config";
const FormItem = Form.Item;
const Option = Select.Option;
const formItemLayout = {
  labelCol: {span: 8},
  wrapperCol: {span: 14},
};
let editAuditDetailSelf;

class EditAuditDetail extends React.Component{
  constructor(props){
    super(props);
    editAuditDetailSelf = this;
    this.state = {
      ruleTypes: [],  //全部渲染信息
      selectedRuleType: '',  //渲染规则参数信息
      selectedItemValue: '',  //渲染取值信息
      ruleDetailInfo: {},
      saveLoading: false,
      isEdit: true,
    };
  }

  componentWillMount() {
    this.getRuleType();
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.slideShow === this.props.slideShow)
      return;
    if (!nextProps.slideShow) {
      this.props.form.resetFields();
      this.setState({
        selectedRuleType: '',
        selectedItemValue: '',
        ruleDetailInfo: {}
      });
      return !1;
    }
    this.props.form.resetFields();
    if(nextProps.ruleDetailInfo){
      const { ruleTypes } = this.state;
      let selectedRuleTypes = [];
      ruleTypes.map(item => {
        item[0].parentType === nextProps.ruleDetailInfo.ruleType && (selectedRuleTypes = item);
      });
      this.setState({
        selectedRuleType: selectedRuleTypes,
        ruleDetailInfo: nextProps.ruleDetailInfo,
        isEdit: true
      },() => {
        const { selectedRuleType } = this.state;
        let itemValue = {};
        selectedRuleType.map(item => {
          item.ruleType === nextProps.ruleDetailInfo.ruleParameter && (itemValue = item);
        });
        this.setState({selectedItemValue:itemValue});
      });
    }else{
      this.setState({
        selectedRuleType: '',
        selectedItemValue: '',
        ruleDetailInfo: {}
      });
    }
  }

  //保存按钮
  handleSave = () => {
    const { ruleDetailInfo, selectedItemValue } = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if(!err){
        if(values.starVal >= 0 && values.endVal < values.starVal){
          message.error(messages('finance-setting.key104'/*金额上限定需不小于金额下限*/));
          return -1;
        }
        this.setState({saveLoading: true});
        let params = JSON.parse(JSON.stringify(ruleDetailInfo));
        params.ruleType = values.ruleType;
        params.ruleParameter = values.ruleParameter;
        params.paramValueType = selectedItemValue.rtnValueType;
        switch (params.paramValueType) {
          case 1002:
            params.itemValue = {
              section: [],
              showValue: []
            };
            params.itemValue.section.push(`${values.starVal}`);
            params.itemValue.section.push(`${values.endVal}`);
            params.itemValue.showValue.push({value:'starVal',showValue:`${values.starVal}`});
            params.itemValue.showValue.push({value:'endVal',showValue:`${values.endVal}`});
            break;
          default :
            params.itemValue = {
              array: [],
              arrays: [],
              showValue: []
            };
            if(Array.isArray(values.itemValue)){
              values.itemValue.map(item => {
                params.itemValue.array.push(item.key);
                params.itemValue.arrays.push(item);
                params.itemValue.showValue.push({value:`${item.key}`,showValue:`${item.showValue}`});
              });
            }else{
              params.itemValue.array.push(values.itemValue);
              let showValue = '';
              selectedItemValue.selectTypeItemList.map(item => {
                item.value === values.itemValue && (showValue = item.option);
              });
              params.itemValue.showValue.push({value:`${values.itemValue}`,showValue:`${showValue}`});
            }
            break;
        };
        params.compareType = values.compareType;
        params.enabled = values.enabled;
        params.ruleId = this.props.ruleId;
        autoAuditService.createDetailRule(params).then(() => {
          this.setState({saveLoading: false});
          this.props.close(true);
        }).catch(() => {
          this.setState({saveLoading: false});
          message.error(messages('finance-setting.key79'/*出错了，请联系管理员*/));
        })
      }
    });
  };

  //获取规则参数类型
  getRuleType = () => {
    autoAuditService.getRuleType().then(res => {
      let parentTypes = [];
      let allRuleTypes = [];
      res.data.map(item => {
        !(~parentTypes.indexOf(item.parentType)) && parentTypes.push(item.parentType);
      });
      parentTypes.map((item,index) => {
        allRuleTypes[index] = [];
        res.data.map(resItem => {
          resItem.parentType === item && allRuleTypes[index].push(resItem);
        });
      });
      this.setState({ruleTypes:allRuleTypes})
    }).catch(() => {
      message.error(messages('finance-setting.key79'/*出错了，请联系管理员*/));
    });
  };

  //改变规则参数类型
  handleChangeRuleType = (value) => {
    const { ruleTypes } = this.state;
    let selectedRuleType = [];
    ruleTypes.map(item => {
      item[0].parentType === Number(value) && (selectedRuleType = item);
    });
    this.setState({
      selectedRuleType: selectedRuleType,
      selectedItemValue: '',
      isEdit: false
    });
    this.props.form.setFieldsValue({ ruleParameter : '', itemValue : '', starVal: '', endVal: '' })
  };

  //改变规则参数
  handleChangeRuleParameter = (value) => {
    const { selectedRuleType } = this.state;
    let itemValue = {};
    selectedRuleType.map(item => {
      item.ruleType === Number(value) && (itemValue = item);
    });
    this.setState({
      selectedItemValue: itemValue,
      isEdit: false
    });
    this.props.form.setFieldsValue({itemValue : ''});
  };

  //渲染取值
  getItemValue = () => {
    const { selectedItemValue } = this.state;
    let selectorItem = {
    };
    if(selectedItemValue.configShowType === 1002){
      selectorItem = {
        title: selectedItemValue.arrayTypeItem.title,
        url: `${config.baseUrl}/api/finance/autoAudit/list/config/values?rtnCode=${selectedItemValue.rtnCode}`,
        columns: this.setChooserColumns(selectedItemValue.arrayTypeItem.columns),
        searchForm: this.setChooserSearchForm(selectedItemValue.arrayTypeItem.labels),
        key: 'relId'
      }
    }
    switch (selectedItemValue.configShowType) {
      case 1002:
        return <Chooser selectorItem={selectorItem}
                        valueKey="relId"
                        showNumber
                        itemMap={true}
                        placeholder={messages('common.select')/*请选择*/}
                        showArrow
                        labelKey={'showValue'}/>;
      case 1000:
        return (<Select>
          {
            selectedItemValue.selectTypeItemList.map(item => {
              return <Option key={item.value} title={item.option}>{item.option}</Option>
            })
          }
        </Select>);
      default:
        return '-';
    };
  };

  //弹框展示表格
  setChooserColumns = (value) => {
    let columns = [
      {
        title: value[0],
        dataIndex: 'showValue',
        key: 'showValue'
      },
      {
        title: value[value.length - 1],
        dataIndex: 'description',
        key: 'description',
        render: value => {
          return <Popover content={value}>{value}</Popover>
        }
      }];
    value[2] && (columns.splice(1,0,{
      title: value[1],
      dataIndex: 'companyName',
      key: 'companyName'
    }));
    return columns;
  };

  //弹框搜索条件
  setChooserSearchForm = (value) => {
    let columns = [];
    value.map(item => {
      columns.push({type: 'input', id: 'keyValue', label: item })
    });
    return columns;
  };

  //初始取值
  getInitialItemVal = (isStarVal = false) => {
    const { ruleDetailInfo, selectedItemValue } = this.state;
    let result = '';
    switch (selectedItemValue.configShowType){
      case 1002:
        result = ruleDetailInfo.itemValue.arrays;
        break;
      case 1000:
        result = ruleDetailInfo.itemValue.array[0];
        break;
      case 1001:
        let sectionNumber = '';
        sectionNumber = isStarVal ? Number(ruleDetailInfo.itemValue.section[0]) : Number(ruleDetailInfo.itemValue.section[1]);
        result = sectionNumber;
        break;
      default:
        result = '';
        break;
    };
    return result;
  };

  render(){
    const { ruleTypes, selectedRuleType, selectedItemValue, ruleDetailInfo, saveLoading, isEdit } = this.state;
    const { getFieldDecorator } = this.props.form;
    return(
      <div className="auto-audit-rule">
        <div className="auto-rule-content">
          <Alert
            message={messages('common.help')/*帮助提示*/}
            description={<div>{messages('finance-setting.key105'/*同一规则详情内取或；*/)}<br/>{messages('finance-setting.key106'/*同规则参数不同规则详情间取交；*/)}<br/>{messages('finance-setting.key107'/*不同规则参数间取交；*/)}</div>}
            type="info"
            showIcon
          />
          <Form onSubmit={this.handleSave} style={{marginTop:'10px'}}>
            <FormItem className="priority-wrap"
                      label={messages('finance-setting.key75'/*规则参数类型*/)} {...formItemLayout}>
              {getFieldDecorator('ruleType', {
                rules: [{
                  required: true, message: messages('common.select')/*请选择*/,
                }],
                initialValue: ruleDetailInfo.ruleType ? `${ruleDetailInfo.ruleType}` : undefined
              })(
                <Select placeholder={messages('common.select')/*请选择*/} onChange={this.handleChangeRuleType}>
                  {
                    ruleTypes.map(item => {
                      return <Option key={item[0].parentType} title={item[0].parentTypeValue}>{item[0].parentTypeValue}</Option>
                    })
                  }
                </Select>
              )}
            </FormItem>
            {
              selectedRuleType && selectedRuleType !== '' &&
              <FormItem className="priority-wrap"
                        label={messages('finance-setting.key76'/*规则参数*/)} {...formItemLayout}>
                {getFieldDecorator('ruleParameter', {
                  rules: [{
                    required: true, message: messages('common.select')/*请选择*/,
                  }],
                  initialValue: ruleDetailInfo.ruleParameter ? `${ruleDetailInfo.ruleParameter}` : undefined
                })(
                  <Select placeholder={messages('common.select')/*请选择*/}  onChange={this.handleChangeRuleParameter}>
                    {
                      selectedRuleType.map(item => {
                        return <Option key={item.ruleType} title={item.ruleTypeValue}>{item.ruleTypeValue}</Option>
                      })
                    }
                  </Select>
                )}
              </FormItem>
            }
            {/*特殊处理区间*/}
            <FormItem className="priority-wrap"
                      label={messages('finance-setting.key77'/*取值方式*/)} {...formItemLayout}>
              {getFieldDecorator('compareType', {
                rules: [{
                  required: true, message: messages('common.select')/*请选择*/,
                }],
                initialValue: ruleDetailInfo.compareType ? ruleDetailInfo.compareType : undefined
              })(
                <Select placeholder={messages('common.select')/*请选择*/}>
                  <Option key='contain' title={messages('finance-setting.key82'/*包含*/)}>{messages('finance-setting.key82'/*包含*/)}</Option>
                  <Option key='exclude' title={messages('finance-setting.key83'/*排除*/)}>{messages('finance-setting.key83'/*排除*/)}</Option>
                </Select>
              )}
            </FormItem>
            {
              selectedItemValue && selectedItemValue !== '' && selectedItemValue.configShowType !== 1001 &&
              <FormItem className="priority-wrap"
                        label={messages('finance-setting.key78'/*取值*/)} {...formItemLayout}>
                {getFieldDecorator('itemValue', {
                  rules: [{
                    required: true, message: messages('common.select')/*请选择*/,
                  }],
                  initialValue: ruleDetailInfo.itemValue ? (isEdit ? this.getInitialItemVal() : '') : undefined
                })(
                  this.getItemValue()
                )}
              </FormItem>
            }
            {
              selectedItemValue && selectedItemValue !== '' && selectedItemValue.configShowType === 1001 &&
              <FormItem {...formItemLayout} label={messages('finance-setting.key78'/*取值*/)} required>
                <Col span={8}>
                  <FormItem>
                    {getFieldDecorator('starVal', {
                      rules: [{
                        required: true,
                        message: messages('common.please.input')/*请输入*/
                      }],
                      initialValue: ruleDetailInfo.itemValue ? (isEdit ? this.getInitialItemVal(true) : '') : undefined
                    })(
                      <InputNumber style={{width: '100%'}} precision={2} min={0} step={0.01}/>
                    )}
                  </FormItem>
                </Col>
                <Col span={1}/>
                <Col span={4}>
                  <div style={{height:'0px',border:'0.5px solid',marginTop:'25%',color:'#666666'}}></div>
                </Col>
                <Col span={1}/>
                <Col span={8}>
                  <FormItem>
                    {getFieldDecorator('endVal', {
                      rules: [{
                        required: true,
                        message: messages('common.please.input')/*请输入*/
                      }],
                      initialValue: ruleDetailInfo.itemValue ? (isEdit ? this.getInitialItemVal(false) : undefined) : undefined
                    })(
                      <InputNumber style={{width: '100%'}} precision={2} min={0} step={0.01}/>
                    )}
                  </FormItem>
                </Col>
              </FormItem>
            }
            <FormItem className="priority-wrap"
                      label={messages('common.column.status')/*状态*/} {...formItemLayout}>
              {getFieldDecorator('enabled',{
                rules: [{
                  required: true
                }],
                initialValue: typeof ruleDetailInfo.enabled === "boolean" ? ruleDetailInfo.enabled : true,
                valuePropName: 'checked'
              })(
                <Switch/>
              )}
            </FormItem>
          </Form>
        </div>
        <div className="footer-operate" style={{backgroundColor:'#ffffff',left:'0px'}}>
          <Button type="primary"  onClick={this.handleSave} style={{margin:'0px 10px'}} loading={saveLoading}>{messages('common.save')/*保存*/}</Button>
          <Button onClick={this.props.close}>{messages('common.cancel')/*取消*/}</Button>
        </div>
      </div>
    )
  }
}

function mapStateToProps(state){
  return {

  }
}

const wrappedEditAuditDetail = Form.create()(EditAuditDetail);
export default connect(mapStateToProps)(wrappedEditAuditDetail);
